<template>
  <div>
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="职位搜索:">
          <el-input
            v-model="keyword"
            placeholder="请你输入搜索的关键字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            :disabled="keyword === ''"
            @click="search"
          >
            搜索
          </el-button>
          <el-button type="primary" size="default" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" size="default" @click="addRole" icon="Plus">
        添加职位
      </el-button>
      <el-table style="margin: 10px 0" :data="allRole">
        <el-table-column
          type="index"
          align="center"
          label="#"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="职位名称"
          align="center"
          prop="roleName"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" width="260px">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="setPermission(row)"
              icon="User"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="updateRole(row)"
              icon="Edit"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`确认删除${row.roleName}？`"
              @confirm="removeRole(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" @click="" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout=" prev, pager, next, jumper,->, sizes,total"
        :total="total"
        @size-change="sizeChange"
        @current-change="getHasRole"
      />
    </el-card>
    <!-- 添加职位与更新已有职位的结构:对话框 -->
    <el-dialog
      :title="RoleParams.id ? '更新职位' : '添加职位'"
      v-model="dialogVisite"
      @close=""
    >
      <el-form :model="RoleParams" :rules="rules" ref="form">
        <el-form-item prop="roleName">
          <el-input
            v-model="RoleParams.roleName"
            placeholder="请输入职位名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="dialogVisite = false">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="save">确定</el-button>
      </template>
    </el-dialog>
    <!-- 抽屉组件:分配职位和权限 -->
    <el-drawer
      title=""
      v-model="drawer"
      direction="rtl"
      size="30%"
      :destroy-on-close="true"
      :show-close="true"
      :wrapperClosable="true"
    >
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <el-tree
          style="max-width: 600px"
          :data="menuArr"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="selectArr"
          :props="defaultProps"
          ref="tree"
        />
      </template>
      <template #footer>
        <el-button type="primary" size="default" @click="">取消</el-button>
        <el-button type="primary" size="default" @click="handler">
          确定
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, nextTick } from 'vue'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqAllMenuList,
  reqSetPermisstion,
  reqRemoveRole,
} from '@/apis/acl/role/index'
import type {
  RoleResponseData,
  Records,
  RoleData,
  MenuresponseData,
  MenuList,
} from '@/apis/acl/role/type'
//引入仓库
import useLayOutSettingStore from '@/store/modules/setting'
import { ElMessage } from 'element-plus'

let layOutSettingStore = useLayOutSettingStore()
//当前页码
let pageNo = ref<number>(1)
let pageSize = ref<number>(10)
let total = ref<number>(400)

//搜索职位的关键字
let keyword = ref<string>('')

//存储全部职位
let allRole = ref<Records>([])

//控制对话框显示与隐藏
let dialogVisite = ref<boolean>(false)

//收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: '',
})

//获取表单组件实例
let form = ref<any>()

//控制抽屉显示与隐藏
let drawer = ref<boolean>(false)

//定义数组存储用户权限的数据
let menuArr = ref<MenuList>([])

//树形控件的实例
let tree = ref<any>()

const defaultProps = {
  children: 'children',
  label: 'name',
}

//准备一个数组:用于存储勾选的节点的ID(四级)
let selectArr = ref<number[]>([])

//更改分页器范围时触发
const sizeChange = () => {
  getHasRole()
}

//获取职位的请求
const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  let result: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  // console.log(result);

  if (result.code === 200) {
    total.value = result.data.total
    allRole.value = result.data.records
  }
}

//搜索按钮的请求
const search = () => {
  //再次发请求
  getHasRole()
  keyword.value = ''
}

//重置按钮的请求
const reset = () => {
  layOutSettingStore.refsh = !layOutSettingStore.refsh
}

//添加职位按钮的回调
const addRole = () => {
  //显示对话框
  dialogVisite.value = true
  //清除数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  })
  //清除验证信息
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

//删除已有的职位
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

//更新职位按钮
const updateRole = (row: RoleData) => {
  //显示对话框
  dialogVisite.value = true
  //存储已有的职位，带有id
  Object.assign(RoleParams, row)
  //清除验证信息
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//确定按钮的回调
const save = async () => {
  //判断表单校验的结果，如果通过就发请求
  let res = await form.value.validate()
  if (res) {
    //添加职位
    let result: any = await reqAddOrUpdateRole(RoleParams)

    if (result.code === 200) {
      //提示文字
      ElMessage({
        type: 'success',
        message: `${RoleParams.id ? '更新成功' : '添加成功'}`,
      })
      //关闭对话框
      dialogVisite.value = false
      //重新获取数据
      getHasRole(RoleParams.id ? pageNo.value : 1)
    } else {
      ElMessage({
        type: 'error',
        message: `${RoleParams.id ? '更新失败' : '添加失败'}`,
      })
    }
  }
}

//分配权限按钮的回调

//已有的职位数据
const setPermission = async (row: RoleData) => {
  drawer.value = true
  //收集当前要分配权限的职位数据
  Object.assign(RoleParams, row)
  let result: MenuresponseData = await reqAllMenuList(RoleParams.id as number)

  if (result.code === 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
//筛选函数
const filterSelectArr = (allData: any[], initArr: any) => {
  allData.forEach((item) => {
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    } else if (item.children.length === 0) {
      if (item.select) {
        initArr.push(item.id)
      }
    }
  })

  return initArr
}

//抽屉确定按钮的回调
const handler = async () => {
  //选中职位的ID
  const roleId = RoleParams.id as number
  //选中节点的ID
  let arr = tree.value.getCheckedKeys()

  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys()
  //下发请求
  let permissionId = arr.concat(arr1)
  //发送请求
  console.log(roleId, permissionId, '@@@')

  let result = await reqSetPermisstion(roleId, permissionId)
  if (result.code === 200) {
    //抽屉关闭
    drawer.value = true
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
    //页面刷新
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: '分配权限失败',
    })
  }
}

/*
const filterSelectArr =  (allData:any[],initArr:any) => {
  allData.forEach((item:any) => {
    if (item.select&&item.level ===4) {
      initArr.push(item.id)
    }
    if (item.children&&item.children.length>0) {
      filterSelectArr(item.children,initArr)
    }
  })
  console.log(initArr);
  
  return initArr
}
*/

//组件挂载完毕
onMounted(() => {
  getHasRole()
})

const validatorRoleName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('职位名称大于两位'))
  }
}

//校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
</style>
